<template>
	<div>
		<div class="crumbs">
			<el-breadcrumb separator="/">
				<el-breadcrumb-item>
					<i class="el-icon-lx-cascades"></i> 资料管理
				</el-breadcrumb-item>
			</el-breadcrumb>
		</div>
		<div class="container">
			<div class="handle-box">
				<el-button type="primary" icon="el-icon-delete" class="handle-del mr10" @click="delAllSelection">批量删除</el-button>
				<el-input v-model="query.title" placeholder="标题" class="handle-input mr10"></el-input>
				<el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
				<el-button type="danger" icon="el-icon-plus" @click="handleAdd">添加</el-button>
			</div>
			<el-table :data="tableData" border class="table" ref="multipleTable" header-cell-class-name="table-header"
			 @selection-change="handleSelectionChange" style="min-height:400px">
				<el-table-column type="selection" width="55" align="center"></el-table-column>
				<el-table-column prop="id" label="ID" width="120" align="center"></el-table-column>
				<el-table-column prop="title" label="标题" width="260" show-overflow-tooltip></el-table-column>
				<el-table-column prop="filename" label="文件名称" width="260" show-overflow-tooltip align="center"></el-table-column>
				<el-table-column prop="createTime" width="210" label="创建时间" :formatter="dateFormat"></el-table-column>
				<el-table-column prop="updateTime" width="210" label="修改时间" :formatter="dateFormat"></el-table-column>
				<el-table-column prop="url" label="路径" width="360" show-overflow-tooltip></el-table-column>
				<el-table-column prop="number" label="下载量" width="90" align="center"></el-table-column>
				<el-table-column prop="type" label="类型" width="120" align="center"></el-table-column>
				<el-table-column label="操作" width="180" align="center">
					<template slot-scope="scope">
						<el-button type="text" icon="el-icon-edit" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
						<el-button type="text" icon="el-icon-download" @click="handleDownload(scope.$index, scope.row)"><font color="#67C23A">下载</font></el-button>
						<el-button type="text" icon="el-icon-delete" class="red" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
			<div class="pagination">
				<el-pagination background layout="total, sizes, prev, pager, next, jumper" :current-page="query.pageIndex"
				 :page-size="query.pageSize" :total="recordTotal" @current-change="handlePageChange" @size-change="handleSizeChange"></el-pagination>
			</div>
		</div>

		<!-- 添加弹出框 -->
		<el-dialog title="添加" :visible.sync="addVisible" width="40%">
			<el-form ref="form" :model="form" label-width="110px">
				<el-form-item label="文件">
					<el-upload ref="upload" class="upload-demo" :on-success="uploadSuccess" :on-error="uploadError" drag action="http://localhost:8081/api/datum/fileUpload"
					 name="file" :auto-upload="false">
						<i class="el-icon-upload"></i>
						<div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
					</el-upload>
				</el-form-item>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="addVisible = false">取 消</el-button>
				<el-button type="primary" @click="saveAdd">上 传</el-button>
			</span>
		</el-dialog>

		<!-- 编辑弹出框 -->
		<el-dialog title="编辑" :visible.sync="editVisible" width="30%">
			<el-form ref="form" :model="form" label-width="110px">
				<el-form-item label="标题">
					<el-input v-model="form.title" placeholder="请输入标题" clearable :style="{width: '100%'}">
					</el-input>
				</el-form-item>
				<el-form-item label="文件名称">
					<el-input v-model="form.filename" placeholder="请输入文件名称" clearable :style="{width: '100%'}">
					</el-input>
				</el-form-item>

				<el-form-item label="文件类型">
					<el-select v-model="form.type" placeholder="请选择">
						<el-option v-for="item in fileType" :key="item.value" :label="item.label" :value="item.value">
						</el-option>
					</el-select>
				</el-form-item>
				</el-form-item>




			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="closeDialog">取 消</el-button>
				<el-button type="primary" @click="editEdit">提 交</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
	/* import { fetchData } from '../../index'; */
	import axios from 'axios';
	import moment from 'moment';

	export default {
		name: 'basetable',
		data() {
			return {
				query: {
					title: '',
					pageIndex: 1, //分页页面索引
					pageSize: 10 //每页面显示的记录数,默认显示10条
				},
				//文件类型
				fileType: [{
					value: '教学资料',
					label: '教学资料'
				}, {
					value: '科研资料',
					label: '科研资料'
				}, {
					value: '学工资料',
					label: '学工资料'
				}, {
					value: '其他资料',
					label: '其他资料'
				}],
				tableData: [],
				multipleSelection: [],
				delList: [],
				addVisible: false,
				editVisible: false,
				pageTotal: 0,
				recordTotal: 0,
				form: {},
				idx: -1,
				id: -1,
				instance: null, //请求实例对象
				searchVisiable: false //搜索状态
			};
		},
		created() {
			this.getUserData(this.query.pageIndex, this.query.pageSize);
		},
		methods: {
			//关闭对话框
			closeDialog() {
				this.addVisible =false;
				this.editVisible = false;
				this.form = {};
			},

			//定义拦截器方法
			interceptor() {
				console.log('请求拦截器调用')
				// 添加请求拦截器，在请求头中加token
				axios.interceptors.request.use(
					config => { //请求成功时，对请求作拦截处理
						if (localStorage.getItem('Authorization')) {
							console.log('读取token,并加入请求头')
							config.headers.Authorization = localStorage.getItem('Authorization');
							console.log(config)
						} else {
							console.log('读取token失败')
						}
						console.log('请求拦截器修改token')
						return config;
					},
					error => { //请求失败时
						return Promise.reject(error);
					});
			},

			getUserData(pageIndex, pageSize) {
				axios.get('/api/datum/page', {
					params: {
						pages: pageIndex,
						size: pageSize
					}
				}).then(res => { //请求成功，返回数据
					console.log(res)
					this.tableData = res.data.data.list; //绑定数据到模型数据
					this.pageTotal = res.data.data.pageTotal;
					this.recordTotal = res.data.data.recordTotal;
				}).catch(err => { //错误处理
					console.log(err)
				})
			},

			// 触发搜索按钮
			handleSearch() {
				//修改搜索状态，在分页时将调用搜索列表方法
				this.searchVisiable = true;
				//搜索第1页
				this.searchListPages(1);
			},
			searchListPages(val) {
				//搜索并请求分页数据
				axios.get('/api/datum/search', {
					params: {
						pages: val,
						size: this.query.pageSize,
						title: this.query.title
					}
				}).then(res => { //请求成功，返回数据
					console.log(res)
					this.tableData = res.data.data.list; //绑定数据到模型数据
					this.pageTotal = res.datga.data.pageTotal;
					this.recordTotal = res.data.data.recordTotal;

				}).catch(err => { //错误处理
					console.log(err)
				})

			},
			// 删除操作
			handleDelete(index, row) {
				//修改搜索状态，在分页时将调用分页列表方法
				this.searchVisiable = false;
				console.log(row)
				// 二次确认删除
				this.$confirm('确定要删除吗？', '提示', {
						type: 'warning'
					})
					.then(() => {
						this.tableData.splice(index, 1); //从数据模型中删除
						//发送请求，从数据库中删除数据行row
						axios.delete('/api/datum/delete', {
							params: {
								id: row.id //row为一条页面数据
							}
						}).then(res => {
							//console.log(res);
							if (res.data.data) { //为true
								this.$message.success('成功删除1条数据');
								location.reload();
							} else {
								this.$message.success('删除数据失败');
							}
						}).catch(err => {
							this.$message.success('删除数据失败');
						})
					})
					.catch(() => {});
			},
			// 多选操作
			handleSelectionChange(val) {
				//console.log(val)
				this.multipleSelection = val;
			},
			//批量删除数据
			delAllSelection() {
				//修改搜索状态，在分页时将调用分页列表方法
				this.searchVisiable = false;
				const length = this.multipleSelection.length;
				//this.delList = this.delList.concat(this.multipleSelection);

				//拼接要删除的数据名称
				for (let i = 0; i < length; i++) {
					//str += this.multipleSelection[i].name + ' ';
					//添加要删除的数据id
					this.delList.push(this.multipleSelection[i].id);
				}
				console.log(this.delList)
				//后端删除对应数据            
				axios.delete('/api/datum/deleteAll', {
						data: {
							list: this.delList
						}
					})
					.then(res => {
						console.log(res)
						if (res.data.data) { //为true
							this.$message.success('成功删除数据' + length + '条');
						} else {
							this.$message.success('删除数据失败');
						}
					})
				this.multipleSelection = [];
				//分页查询当前索引页面
				this.handlePageChange(this.query.pageIndex)
			},
			//添加操作
			handleAdd() {
				this.addVisible = true;
			},
			saveAdd() {
				this.$refs.upload.submit();
				this.addVisible = false;
				location.reload();
			},
			//上传成功
			uploadSuccess() {
				this.$message.success('文件上传成功！');
			},
			//上传失败
			uploadError() {
				this.$message.error('文件上传失败！');
			},
			// 编辑操作
			handleEdit(index, row) {
				this.idx = index; //编辑数据的索引
				this.form = row;
				this.editVisible = true;
				console.log(index)
			},
			// 保存编辑
			editEdit() {
				if (this.idx > -1) { //编辑数据
					//修改搜索状态，在分页时将调用分页列表方法
					this.searchVisiable = false;
					this.editVisible = false;
					var data = this.form;
					this.interceptor();
					axios.put('/api/datum/update', data).then(res => {
						console.log("数据更新成功")
						this.$set(this.tableData, this.idx, this.form);
						this.$message.success(`修改第 ${this.idx + 1} 行成功`);
						this.idx = -1;
						this.form = {}
						location.reload();
					}).catch(err => {
						console.log(err)
						this.idx = -1;
						this.form = {}
					})
				} else { //新建
					this.$message.error("编辑失败！");
					this.editVisible = false;
				}
			},
			//下载操作
			handleDownload(index, row) {
				window.location.href = "http://localhost:9520/api/api/datum/fileDownload?id="+row.id;
			},
			
			// 分页
			// 分页导航
			handlePageChange(val) { //val为页码索引      	

				if (this.searchVisiable) { //是搜索分页
					this.searchListPages(val)
				} else { //是列表分页
					this.query.pageIndex = val;
					var pageSize = this.query.pageSize;
					//按页码、每页记录数，请求数据
					this.getUserData(val, pageSize);
				}
			},
			// 每页显示的条数
			handleSizeChange(val) {
				// 改变每页显示的条数 
				this.query.pageSize = val
				// 点击每页显示的条数时【10，20】，显示第一页
				this.getUserData(1, val)
				// 注意：在改变每页显示的条数时，要将页码显示到第一页
				this.query.pageIndex = 1
			},
			//日期格式处理
			dateFormat(row, column, cellValue, index) {
				var date = cellValue
				if (!date) {
					return ''
				}
				return moment(date).format('YYYY年MM月DD日 HH:mm:ss')
			}
		}
	};
</script>

<style scoped>
	.handle-box {
		margin-bottom: 20px;
	}

	.handle-select {
		width: 120px;
	}

	.handle-input {
		width: 300px;
		display: inline-block;
	}

	.table {
		width: 100%;
		font-size: 14px;
	}

	.red {
		color: #ff0000;
	}

	.mr10 {
		margin-right: 10px;
	}

	.table-td-thumb {
		display: block;
		margin: auto;
		width: 40px;
		height: 40px;
	}
</style>
